from functools import wraps
from flask import request, current_app
from flask_login import current_user

from functools import wraps
from flask import request, current_app
from flask_login import current_user


def admin_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        # 如果请求方法在 EXEMPT_METHODS 或者当前应用禁用了登录检查，则跳过验证
        if request.method in current_app.config.get("EXEMPT_METHODS", []) or current_app.config.get("LOGIN_DISABLED"):
            pass
        # 检查用户是否登录
        elif not current_user.is_authenticated:
            return current_app.login_manager.unauthorized()
        # 检查用户是否是超级用户
        elif getattr(current_user, "is_superuser", 0) != 1:
            return current_app.login_manager.unauthorized()  # 返回未授权的响应

        # 处理异步函数
        if callable(getattr(current_app, "ensure_sync", None)):
            return current_app.ensure_sync(func)(*args, **kwargs)

        # 返回原始函数的结果
        return func(*args, **kwargs)

    return decorated_view


